package com.spark.analysis

import org.apache.commons.pool2.impl.GenericObjectPoolConfig

//object RedisClient {
//  val prop = new Properties()
//  //加载配置文件
//  prop.load(
//      this.getClass.getClassLoader.getResourceAsStream("redis.properties"))
//      val redisHost: String = prop.getProperty("jedis.host")
//      val redisPort: String = prop.getProperty("jedis.port")
//      val redisTimeout: String = prop.getProperty("redis.timeout")
//      println(s"redisHost:${redisHost},redisPort:${redisPort},redisTimeout:${redisTimeout}")
//      lazy val pool = new JedisPool(new GenericObjectPoolConfig(),
//        redisHost, redisPort.toInt,
//        redisTimeout.toInt)
//      lazy val hook = new Thread {
//        override def run = {
//          println("Execute hook thread: " + this)
//          pool.destroy()
//        }
//  }
//}
import java.io.IOException
import java.util.Properties
import redis.clients.jedis.{Jedis,JedisPool, JedisPoolConfig}

object RedisClient {
  // 加载配置
  val prop = new Properties()
  val resource = getClass.getClassLoader.getResourceAsStream("redis.properties")
  if (resource == null) throw new IOException("redis.properties not found in classpath")
  prop.load(resource)

  // 解析配置（带校验和默认值）
  val host: String = prop.getProperty("jedis.host", "localhost")
  val port: Int = prop.getProperty("jedis.port", "6379").toInt
  val timeout: Int = prop.getProperty("redis.timeout", "2000").toInt
  val password: String = prop.getProperty("jedis.password", null) // 无密码时为 null

  // 配置连接池
  val poolConfig: JedisPoolConfig = new JedisPoolConfig()
  poolConfig.setMaxTotal(50)    // 最大连接数（根据需求调整）
  poolConfig.setMaxIdle(10)     // 最大空闲连接
  poolConfig.setMinIdle(5)      // 最小空闲连接
  poolConfig.setTestOnBorrow(true) // 借连接时测试有效性

  // 创建 JedisPool（支持密码）
  val pool: JedisPool = if (password != null && password.nonEmpty) {
    new JedisPool(poolConfig, host, port, timeout, password)
  } else {
    new JedisPool(poolConfig, host, port, timeout)
  }

  // 注册 JVM 关闭钩子（显式实现 Runnable）
  Runtime.getRuntime.addShutdownHook(new Thread(new Runnable {
    override def run(): Unit = {
      pool.destroy()
      println("JedisPool destroyed successfully.")
    }
  }))

  // 工具方法：获取 Jedis 连接（自动释放）
  def useJedis[T](block: Jedis => T): T = {
    val jedis = pool.getResource()
    try {
      block(jedis)
    } finally {
      jedis.close() // 释放连接回池
    }
  }
}
